package dao.implementation;

import java.sql.Date;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;

import dao.ArticleDAO;
import data.Article;
import utils.JDBCUtil;

public class ArticleDAOImplementation implements ArticleDAO
{

	@Override
	public Article selectByID(int article_id)
	{
		String condition = ArticleDAO.COLUMN_NAME_ID
				+ "='"
				+ article_id
				+ "'";
		ResultSet set = JDBCUtil.selectRow(ArticleDAO.TABLE_NAME, condition);
		if (set == null)
			return null;
		
		
		try
		{
			String title = set.getString(ArticleDAO.COLUMN_NAME_TITLE);
			int user_id = set.getInt(ArticleDAO.COLUMN_NAME_USER_ID);
			String author = set.getString(ArticleDAO.COLUMN_NAME_AUTHOR);
			Date upload_date = set.getDate(ArticleDAO.COLUMN_NAME_UPLOAD_DATE);
			String content = set.getString(ArticleDAO.COLUMN_NAME_CONTENT);
			return new Article
					(
						article_id,
						title,
						user_id,
						author,
						upload_date,
						content
					);
		}
		catch (SQLException e) {e.printStackTrace();}
		
		return null;
	}



	@Override
	public void insert(Article article)
	{
		JDBCUtil.insert
			(
				ArticleDAO.TABLE_NAME,
				String.valueOf(article.id),
				article.title,
				String.valueOf(article.user_id),
				article.author,
				article.upload_date.toString(),
				article.content
			);
	}
	
	
	@Override
	public void update(Article article)
	{
		HashMap<String, String> map = new HashMap<String, String>();
		map.put(ArticleDAO.COLUMN_NAME_ID, String.valueOf(article.id));
		map.put(ArticleDAO.COLUMN_NAME_TITLE, article.title);
		map.put(ArticleDAO.COLUMN_NAME_USER_ID, String.valueOf(article.user_id));
		map.put(ArticleDAO.COLUMN_NAME_AUTHOR, article.author);
		map.put(ArticleDAO.COLUMN_NAME_UPLOAD_DATE, article.upload_date.toString());
		map.put(ArticleDAO.COLUMN_NAME_CONTENT, article.content);
		
		String condition = ArticleDAO.COLUMN_NAME_ID
				+ "='"
				+ article.id
				+ "'";
		JDBCUtil.update(ArticleDAO.TABLE_NAME, map, condition);
	}
	
	
	@Override
	public void update(int article_id, String column_name, String value)
	{
		String condition = ArticleDAO.COLUMN_NAME_ID
				+ "='"
				+ article_id
				+ "'";
		JDBCUtil.updateOneValue(ArticleDAO.TABLE_NAME, column_name, value, condition);
	}
	
	
	@Override
	public void updateContent(int article_id, String content)
	{
		this.update(article_id, ArticleDAO.COLUMN_NAME_CONTENT, content);
	}
	
	
	@Override
	public int count()
	{
		return JDBCUtil.countRow(ArticleDAO.TABLE_NAME, ArticleDAO.COLUMN_NAME_ID);
	}
	
	


	
}




